package cn.com.surker.production.service.impl;

import cn.com.surker.common.MessageCenterException;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.enums.production.ProductionContractTypeEnum;
import cn.com.surker.oa.dao.OaProductionContractDao;
import cn.com.surker.oa.vo.ProductionContractVo;
import cn.com.surker.production.entity.ProductionPumpPrice;
import cn.com.surker.production.entity.ProductionPumpSubsidy;
import cn.com.surker.production.dao.ProductionPumpSubsidyDao;
import cn.com.surker.production.service.PumpSubsidyService;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.surker.spring.RestResultDto;

import javax.annotation.Resource;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
* <p>
    * 泵送合同补贴表 服务实现类
    * </p>
*
* @author admin
* @since 2024-12-05
*/
public abstract class PumpSubsidyServiceImpl extends ServiceImpl<ProductionPumpSubsidyDao, ProductionPumpSubsidy> implements PumpSubsidyService {

    @Resource
    protected ProductionPumpSubsidyDao contractSubsidyDao;
    @Resource
    protected OaProductionContractDao productionContractDao;

    /**
     * 查询生产合同泵送补贴信息
     * @param contractId
     * @return
     */
    public Map<String, List<ProductionPumpSubsidy>> findByContract(Long contractId) {
        if (StringUtils.isNull(contractId))
            return null;
        QueryWrapper<ProductionPumpSubsidy> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("contract_id", contractId);
        query.orderByDesc("take_time");
        List<ProductionPumpSubsidy> priceList = contractSubsidyDao.selectList(query);
        if (priceList == null || priceList.size() == 0)
            return null;
        Map<String, List<ProductionPumpSubsidy>> map = new LinkedHashMap<>();
        for (int i = 0; i < priceList.size(); i++) {
            ProductionPumpSubsidy price = priceList.get(i);
            String takeTime = DateUtil.convertString(price.getTakeTime());
            if (map.containsKey(takeTime)) {
                List<ProductionPumpSubsidy> tempList = map.get(takeTime);
                tempList.add(price);
                map.put(takeTime, tempList);
            } else {
                List<ProductionPumpSubsidy> tempList = new ArrayList<>();
                tempList.add(price);
                map.put(takeTime, tempList);
            }
        }
        return map;
    }

    /**
     * 新增生产合同泵送补贴信息
     * @return
     */
    public RestResultDto savePrice(ProductionPumpSubsidy pumpSubsidy) {
        if (pumpSubsidy == null)
            throw new MessageCenterException("参数错误");
        if (StringUtils.isNull(pumpSubsidy.getOrgId()))
            throw new MessageCenterException("合同公司信息为空");
        if (StringUtils.isNull(pumpSubsidy.getContractId()))
            throw new MessageCenterException("合同信息为空");
        if (StringUtils.isNull(pumpSubsidy.getPumpTypeId()))
            throw new MessageCenterException("泵送类型为空");
        if (StringUtils.isNull(pumpSubsidy.getPumpNormId()))
            throw new MessageCenterException("泵送规格为空");
        if (StringUtils.isNull(pumpSubsidy.getPrice()))
            throw new MessageCenterException("运输单价为空");
        if (StringUtils.isNull(pumpSubsidy.getTakeTime()))
            throw new MessageCenterException("生效时间为空");
        if (StringUtils.isNull(pumpSubsidy.getCountType()))
            throw new MessageCenterException("泵送补贴计算方式为空");

        Date nowDate = new Date();
        ProductionContractVo contract = productionContractDao.selectByIdVo(pumpSubsidy.getContractId());
        if (contract == null || contract.getStatus().intValue() == 1)
            throw new MessageCenterException("运输合同不存在或已被删除");
        if (contract.getType().intValue() != ProductionContractTypeEnum.PUMP.getCode())
            throw new MessageCenterException("运输合同类型错误");
//        ProductionTransportPrice transportPrice = new ProductionTransportPrice(orgId, contractId, supplierId, takeDate,
//                transportType, countType, carModel, isSpeed, isLimit, minDistance, maxDistance, minStere, maxStere,price);
        pumpSubsidy.setCreateTime(nowDate);
//        transportPrice.setCreator(creator);
//        transportPrice.setRemark(remark);
//        transportPrice.setStatus(0);
        ProductionPumpSubsidy tempPumpSubsidy = contractSubsidyDao.findTakePrice(pumpSubsidy);
        if (tempPumpSubsidy != null) {
            tempPumpSubsidy.setUpdateTime(nowDate);
            tempPumpSubsidy.setUpdator(pumpSubsidy.getCreator());
            tempPumpSubsidy.setPrice(pumpSubsidy.getPrice());
            tempPumpSubsidy.setCalcType(pumpSubsidy.getCalcType());
            tempPumpSubsidy.setPriceType(pumpSubsidy.getPriceType());
            tempPumpSubsidy.setTakeTime(pumpSubsidy.getTakeTime());
            if (!StringUtils.isNull(pumpSubsidy.getExpireTime()))
                tempPumpSubsidy.setExpireTime(pumpSubsidy.getExpireTime());
            Integer code = contractSubsidyDao.updateById(tempPumpSubsidy);
            if (code > 0) {

                return RestResultDto.success("保存泵送补贴成功", tempPumpSubsidy);
            }
            return RestResultDto.fail("保存运输单价异常");
        }
        Integer code = contractSubsidyDao.insert(pumpSubsidy);
        if (code > 0) {
            return RestResultDto.success("保存成功", pumpSubsidy);
        }
        return RestResultDto.fail("保存运输单价异常");
    }
    /**
     * 修改泵送补贴信息
     * @return
     */
    public RestResultDto updatePrice(ProductionPumpSubsidy pumpSubsidy) {
        if (pumpSubsidy == null || StringUtils.isNull(pumpSubsidy.getId()))
            throw new MessageCenterException("参数错误");
        ProductionPumpSubsidy pumpPrice = contractSubsidyDao.selectById(pumpSubsidy.getId());
        if (pumpPrice == null || pumpPrice.getStatus() == 1)
            throw new MessageCenterException("生产泵送补贴不存在或该单价已被禁用");
//        ProductionTransportPrice newTransportPrice = new ProductionTransportPrice(transportPrice.getOrgId(), transportPrice.getContractId(),
//                transportPrice.getSupplierId(), transportPrice.getTakeTime(), transportType, countType, carModel,
//                isSpeed, isLimit, minDistance, maxDistance, minStere, maxStere,price);
        Date nowDate = new Date();
        pumpSubsidy.setUpdateTime(nowDate);
        Integer code = contractSubsidyDao.updateById(pumpSubsidy);
        if (code > 0) {
            return RestResultDto.success("更新成功", pumpPrice);
        }
        return RestResultDto.fail("更新运输单价异常");
    }

    /**
     * 禁用合同
     * @param id
     * @param status
     * @return
     */
    public RestResultDto updateStatus(Long id, Integer status, String creator) {
        if (StringUtils.isAllParamNull(id, status))
            throw new MessageCenterException("参数错误");
        ProductionPumpSubsidy transportPrice = contractSubsidyDao.selectById(id);
        if (transportPrice == null)
            throw new MessageCenterException("泵送补贴信息不存在");
        transportPrice.setStatus(status);
        transportPrice.setUpdateTime(new Date());
        transportPrice.setUpdator(creator);
        Integer code = contractSubsidyDao.updateById(transportPrice);
        if (code > 0) {
            return RestResultDto.success("更新成功", transportPrice);
        }
        return RestResultDto.fail("更新泵送补贴异常");
    }

	@Override
	public Double findByContractV2(Long orgId, Long pumpConId, Long pumpTypeId, Long pumpNormId, String pumpTime) {
		if (pumpConId == null || StringUtils.isBlank(pumpTime) || (pumpTypeId == null && pumpNormId == null)) {
			return null;
		}
		QueryWrapper<ProductionPumpSubsidy> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("org_id", orgId);
		qw.eq("contract_id", pumpConId);
		if (pumpTypeId != null) {
			qw.eq("pump_type_id", pumpTypeId);
		}
		if (pumpNormId != null) {
			qw.eq("pump_norm_id", pumpNormId);
		}
		qw.le("take_time", pumpTime);
		qw.and(e -> {
			//	截止时间大于运输时间
			e.isNull("take_time").or().gt("take_time", pumpTime);
		});
		qw.last("limit 1");
		ProductionPumpSubsidy productionPumpPrice = contractSubsidyDao.selectOne(qw);
		if (productionPumpPrice != null) {
			Double price = productionPumpPrice.getPrice();
			return price;
		}
		return null;
	}
}